package com.kun.rental.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kun.rental.entity.CarrentalInfo;
import com.kun.rental.service.ICarrentalInfoService;
import com.kun.rental.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 *  车辆信息
 * </p>
 *
 * @author ikun
 * @since 2024-07-04
 */
@RestController
@RequestMapping("/rental/carrentalInfo")
public class CarrentalInfoController {

    @Autowired
    private ICarrentalInfoService carrentalInfoService;

    @Value("${carrental.info.maintain-mileage}")
    private Integer maintainMileage;


    /**
     * 分页查询
     * @param start
     * @param size
     * @param carrentalInfo
     * @return
     */
    @PostMapping("/{start}/{size}")
    public Result search(@PathVariable int start,
                         @PathVariable int size,
                         @RequestBody CarrentalInfo carrentalInfo){
        Page<CarrentalInfo> page = new Page<>(start, size);
        return Result.success(carrentalInfoService.searchByPage(page, carrentalInfo));
    }


    /**
     * 新增
     * @param carrentalInfo
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody CarrentalInfo carrentalInfo){
        //设置应保次数和实报次数
        int i =  carrentalInfo.getMileage() / maintainMileage;
        carrentalInfo.setExpectedNum(i);    //应保次数
        carrentalInfo.setActualNum(i);      //实报次数
        return carrentalInfoService.save(carrentalInfo)?Result.success():Result.fail();
    }


    /**
     * 删除
     * @param ids
     * @return
     */
    @DeleteMapping("/delete/{ids}")
    public Result delete(@PathVariable String ids){
        return Result.success(carrentalInfoService.delete(ids));
    }


    /**
     * 修改
     * @param carrentalInfo
     * @return
     */
    @PutMapping("/update")
    public Result update(@RequestBody CarrentalInfo carrentalInfo){
        int i =  carrentalInfo.getMileage() / maintainMileage;
        carrentalInfo.setExpectedNum(i);    //应保次数
        carrentalInfo.setActualNum(i);      //实报次数
        return carrentalInfoService.updateById(carrentalInfo)?Result.success():Result.fail();
    }


    /**
     * 查询车牌车辆是否存在
     * @param carrentalInfo
     * @return
     */
    @PostMapping("/exist")
    public Result exist(@RequestBody CarrentalInfo carrentalInfo) {
        CarrentalInfo info = carrentalInfoService.selectByCarrentalNum(carrentalInfo.getNum());
        return ObjectUtil.isNotEmpty(info) ?
                Result.success().setMessage("have") : Result.success().setMessage("none");
    }


    /**
     * 查询需要保养的车辆信息
     * @return
     */
    @GetMapping("/toBeMaintain")
    public Result toBeMaintain(){
        return Result.success(carrentalInfoService.toBeMaintain());
    }


}
